import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
import { message } from 'ant-design-vue'

export const useApiStore = defineStore('api', () => {
  // 状态
  const apis = ref([])
  const loading = ref(false)
  const currentApi = ref(null)
  const testResult = ref(null)

  // 动作
  const fetchAPIs = async (params = {}) => {
    loading.value = true
    try {
      const response = await axios.get('/api/apis', { params })
      return response.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const createAPI = async (data) => {
    try {
      const response = await axios.post('/api/apis', data)
      return response.data
    } catch (error) {
      throw error
    }
  }

  const updateAPI = async (id, data) => {
    try {
      const response = await axios.put(`/api/apis/${id}`, data)
      return response.data
    } catch (error) {
      throw error
    }
  }

  const deleteAPI = async (id) => {
    try {
      await axios.delete(`/api/apis/${id}`)
    } catch (error) {
      throw error
    }
  }

  const testAPI = async (id) => {
    try {
      const response = await axios.post(`/api/apis/${id}/test`)
      return response.data
    } catch (error) {
      throw error
    }
  }

  const getAPI = async (id) => {
    try {
      const res = await axios.get(`/api/apis/${id}`)
      if (res.code === 200) {
        currentApi.value = res.data
        return true
      }
      return false
    } catch (error) {
      console.error('获取API详情失败:', error)
      return false
    }
  }

  const fetchStatistics = async (period = 'day') => {
    try {
      const response = await axios.get('/api/statistics', {
        params: { period }
      })
      return response.data
    } catch (error) {
      throw error
    }
  }

  return {
    apis,
    loading,
    currentApi,
    testResult,
    fetchAPIs,
    createAPI,
    updateAPI,
    deleteAPI,
    testAPI,
    getAPI,
    fetchStatistics
  }
}) 